<template>
  <div>
    <el-dialog title="服务金额结算" :model-value="props.modelValue" width="900px" @close="$emit('update:modelValue', false)">
      <el-form :model="formData" ref="formRef" :rules="rules" label-suffix=":">
        <el-form-item label="任务名称">
          <el-input disabled :model-value="props.selectedRow?.name"></el-input>
        </el-form-item>
        <el-form-item label="自由职业者" prop="userList">
          <el-table @selection-change="handleSelectionChange" :data="tableData" border>
            <el-table-column type="selection" align="center" width="55" label="操作" />
            <el-table-column prop="name" align="center"  label="竞标人" width="60" />
            <el-table-column prop="phone" align="center"  label="手机号" width="120" />
            <el-table-column prop="cardId" align="center"   label="身份证号" />
            <el-table-column prop="cost1" align="center"  label="服务金额（元）" width="120"  >
              <template #default="{row}">
                <el-input-number style="width: 90%;" controls-position="right" v-model="row.cost1"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="taskStatus" align="center" label="项目状态" width="90">
              <template #default="scope">
                <dict-tag :options="woker_task_status" :value="scope.row.taskStatus" />
              </template>
              </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="产品选择" prop="proId" v-if="proShow">
          <div style="height: 420px;width: 100%;" class="radio-wrapper">
            <el-radio-group v-model="formData.proId" class="ml-4" style="flex-direction: column;align-items: flex-start;" >
                <template v-for="item in merchantOptions" >
                  <div style="border: 1px dashed #ccc;padding-left:5px;">
                    <el-radio :label="item.proId" >{{getProInfo(item)}}</el-radio>
                    <div class="radio-card" style="padding-left:15px;">
                      <!--
                      <el-radio :label="item.id" >
                        <span class="ticket-title">增值税专用发票</span>
                       </el-radio>-->
                        <el-descriptions :column="1">
                          <el-descriptions-item label="产品编号:"><span style="font-weight: 700;">{{item?.proNo}}</span></el-descriptions-item>
                          <el-descriptions-item label="计费模式:">
                          <span style="font-weight: 700;">{{
                            item?.chargeMode === 1 ? '个人应得计费' :  item?.chargeMode === 2 ? '开票金额计费' : ''
                          }}</span></el-descriptions-item>

                          <el-descriptions-item label="服务费率:"><span style="font-weight: 700;">{{item?.serviceCharge}}%</span></el-descriptions-item>
                          <el-descriptions-item label="单人单月发放上限:"><span style="font-weight: 700;">{{proxy.convertFenToYuan(item?.maxMonth) || ''}}元</span></el-descriptions-item>
                          <el-descriptions-item label="开票项目:">
                           <div style="white-space: normal;"> {{item?.invoiceItems}}</div>
                          </el-descriptions-item>
                        </el-descriptions>
                      </div>
                   </div>
                </template>
            </el-radio-group>
          </div>
          <!--
          <div style="height: 300px;width: 100%;" class="radio-wrapper">
            <el-radio-group style="width: 100%" v-model="formData.proId">
                <el-radio  label="11">
                  dsafdsa
                </el-radio>
              <el-radio  label="22">
                dsafdsa
              </el-radio>
              <template v-for="item in merchantOptions" >
                <div class="radio-card">
                  <el-radio :label="item.id" >
                    <span class="ticket-title">增值税专用发票</span>
                   </el-radio>
                    <el-descriptions :column="1">
                      <el-descriptions-item label="产品编号:">{{item?.proNo}}</el-descriptions-item>
                      <el-descriptions-item label="服务费率:">{{item?.costServiceCharge}}%</el-descriptions-item>
                      <el-descriptions-item label="单人单月发放上限:">{{item?.max || ''}}</el-descriptions-item>
                      <el-descriptions-item label="开票项目:">
                       <div style="white-space: normal;"> {{item?.invoiceItems}}</div>
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
               </template>


              <el-radio v-for="item in merchantOptions" :label="item.id" style="width: 100%;">
                <span class="ticket-title">增值税专用发票</span>
                <div class="radio-card product-detail">
                  <el-descriptions :column="1">
                    <el-descriptions-item label="产品编号:">{{item?.proNo}}</el-descriptions-item>
                    <el-descriptions-item label="服务费率:">{{item?.costServiceCharge}}%</el-descriptions-item>
                    <el-descriptions-item label="单人单月发放上限:">{{item?.max || ''}}</el-descriptions-item>
                    <el-descriptions-item label="开票项目:">
                      {{item?.invoiceItems}}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </el-radio>
            </el-radio-group>
          </div>-->
        </el-form-item>
        <el-form-item label="服务费承担方" prop="serviceChargeType">
          <el-radio-group style="width: 100%" v-model="formData.serviceChargeType">
            <el-radio :label="1">用工企业承担</el-radio>
            <el-radio :label="2">自由职业者承担</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="批次号" prop="no">
          <el-input v-model="formData.no">
            <template #prepend>{{moment().format('YYYYMMDD')}}-</template>
          </el-input>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="$emit('update:modelValue', false)">关闭</el-button>
          <el-button type="primary" @click="onSubmit" :loading="loading"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
    <QdResult  @onClose="onClose"  v-model="settleModalVisible" @addBill="onAddBill"   :success="uploadResult.success"  :list="uploadResult.list" :imported="uploadResult.imported" ></QdResult>
  </div>
</template>

<script setup lang="ts">
import useUserStore from '@/store/modules/user'
import QdResult from  './qdResult.vue'
import moment from 'moment';
import {selBtByMs,addBill} from "@/api/settlementManagement/settlementPayment/index"
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const {invoice_type} = toRefs(proxy?.useDict("invoice_type"));
const {woker_task_status} = toRefs(proxy?.useDict("woker_task_status"));
const emit = defineEmits(['update:modelValue','onSuccess'])
const proShow = ref(false);

const isNumericString =  (str:any)=> {
  return /^\d+$/.test(str);
}

const numberValida = (rule: any, value: string, callback: any) => {
  if (!isNumericString(value)) {
    callback(new Error("格式错误,请输入数字"));
  } else {
    callback();
  }
};

  const rules = reactive({
    userList: [{ required: true,message: "请选择自由职业者", trigger: 'change' }],
    proId: [{ required: true, message: "请选择产品", trigger: 'blur' }],
    no: [{ required: true, message: "请输入批次号", trigger: 'blur' }, {
    required: true,
    validator: numberValida,
    trigger: "blur"
  }  ],
    serviceChargeType: [{ required: true, message: "请选择服务费承担方", trigger: 'blur' }],
})
const merchantOptions = ref([])
const radio1 = ref();
const formRef = ref();
const formData = reactive({
    no: '',
    busType: '',
    taskId: '',
    name: '',
    proId: '',
    proNo: '',
    userList: [],
    serviceChargeType: 1, // 1:用工企业承担 2:自由职业者承担
})

const uploadResult = reactive({
  success: false,
  allRecords:0,
  list: [],
  params:{},
  imported: false
})
const settleModalVisible = ref(false)

const onClose = () => {
  uploadResult.success = false
  uploadResult.imported = false
  uploadResult.params = {}
  uploadResult.list = []
}

const projectDetails = computed(() => {
  return merchantOptions.value.find(item => item.proId === formData.proId) || {}
})



const getInvoiceType = (val)=>{
  return proxy?.getDicValue(val,invoice_type.value);
}

const getProInfo = (item:any)=>{
    let chargeMode = item?.chargeMode === 1 ? '个人应得计费' :  item?.chargeMode === 2 ? '开票金额计费' : ''
    return item.proNo +"-"+getInvoiceType(item.invoiceType)+"-"+chargeMode+"-"+ item.serviceCharge+"%";
}



const tableData = ref([
    {
        // name: '张三',
        // phone: 1888888888,
        // cardId: '411528199999999999',
        // cost: 9999,
        // status: 'NORMAL',
    }
])

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  if(val.length == 0){
    proShow.value = false;
  }else{
    proShow.value = true;
  }
  multipleSelection.value = val;
  formData.userList = val.map(item => {
    return {
     workerName:item.name,
     cardId:item.cardId,
     moneyDecimal:item.cost1,
     billRemark:'',
     }
  })
}

  const loading = ref(false)


  const props = defineProps({
      modelValue: {
          type: Boolean
      },
      selectedRow: {},
  })


  watch(() => props.selectedRow, async data => {
    const defaultProvider = useUserStore().defaultProvider;

    const { response } = await useRequest('/payment/bill/balanceEnrollList', 'GET', {
        params: {
            taskId: data.id
        }
    }, { immediate: true })

    if ( response.value?.rows.length) {
        let list = response.value?.rows;
        list.map(item=>{
            item.cost1 = proxy?.convertFenToYuan(item.cost);
        })
        tableData.value = list;
    }

    const { data: merchantList } = await useRequest('/payment/merchantProduct/queryList', 'GET', {
    params: { busType: props.selectedRow.busType, sydId: defaultProvider.sydId }
  }, { immediate: true })


  if (merchantList) {
    merchantOptions.value = merchantList.value
  }


  })

  const getRandomInt = (min, max) => {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

const onAddBill =()=>{
  proxy?.$modal.loading("正在提交数据，请稍候...");
    addBill({
        ...uploadResult.params,
        detail:uploadResult.list
    }).then((res)=>{
        onClose();
        emit('update:modelValue', false);
        emit('onSuccess');
        proxy?.$modal.msgSuccess("提交成功");
    }).finally(()=>{
        proxy?.$modal.closeLoading();
    });
}


  const onSubmit = () => {

    formRef.value?.validate(async passed => {
        if(passed){
            let defaultProvider = useUserStore().defaultProvider;
            loading.value = true
            const submitData = {
              ...formData,
               // no: `${moment().format('YYYYMMDD')}-PD-${getRandomInt(0,99)}`,
              no: `${moment().format('YYYYMMDD')}-${formData.no}`,
              maxMonth: projectDetails.value.maxMonth,
              chargeMode: projectDetails.value.chargeMode,
              merId: defaultProvider.merId,
              sydNo: defaultProvider.sydNo,
              invoiceType: projectDetails.value.invoiceType,
              channelCode: projectDetails.value.channelCode,
              proNo: projectDetails.value.proNo,
              merNo: defaultProvider.merNo,
              taskId: props.selectedRow.id,
              taskNo: props.selectedRow.no,
              busType:props.selectedRow.busType,
              settlementStyle: projectDetails.value.settlementStyle,
              sydId: defaultProvider.sydId,
              sydNo:defaultProvider.sydNo,
              passage:defaultProvider.bankType,
              serviceChargeRate: projectDetails.value.serviceCharge,
              details: formData.userList
            }
            console.log(submitData);
            useRequest('/payment/bill/qdPaymentImport', "POST", {
                data: submitData
            }, { immediate: true,
                onFinish() {
                    loading.value = false
                },
                onSuccess: (data) => {
                    // emit('update:modelValue', false)
                      settleModalVisible.value = true;
                      const {list,errorList,analysis,allRecords} = data;

                      uploadResult.success =  errorList.length> 0 ?false:true,
                      uploadResult.imported = true
                      uploadResult.params = submitData
                      uploadResult.list = list
                      uploadResult.allRecords = allRecords;
                      // emit('onSuccess', {
                      //   code: 200,
                      //   success: errorList.length> 0 ?false:true,
                      //   allRecords:allRecords,
                      //   analysis:analysis,
                      //   msg: '操作成功',
                      //   data: {
                      //     list: list,
                      //     errorList: errorList,
                      //     analysis: 'analysis',
                      //   }
                      // })
                }
             })



        }

    });

    return ;
    loading.value = true

    // TODO 确认接口入参
    const submitData = {
        ...formData,
        ...props.selectedRow,
        ...projectDetails.value
    }
    useRequest('/payment/bill/qdPaymentImport', "POST", {
        data: submitData
    }, { immediate: true,
        onFinish() {
            loading.value = false
        },
        onSuccess: (data) => {
            emit('update:modelValue', false)
        }
     })

  }


</script>

<style lang="scss" scope>



:deep(.el-descriptions__body .el-descriptions__table:not(.is-bordered) .el-descriptions__cell) {
       padding-bottom: 2px;
  }



.radio-wrapper {
    width: 100%;
    height: 400px;
    overflow: auto;
    border: 1px solid #ccc;
    padding: 10px;
    /*.radio-card {
        padding: 35px 20px 0 20px;
        width: 640px;
        border: 1px dashed #ccc
    }
    .ticket-title {
            position: absolute;
            top: 32px;
            left: 40px;
        }
    .el-radio {
        display: block;
        width: 100%;
        height: 220PX;
        position: relative;
        .el-radio__input {
            position: absolute;
            top: 40px;
            left: 20px;
        }
    }*/
}
</style>
